package com.wu.foodsafetyplayer.app;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.google.gson.JsonSyntaxException;
import com.wu.foodsafetyplayer.R;
import com.wu.foodsafetyplayer.http.CommonOkHttpClient;
import com.wu.foodsafetyplayer.utils.ACache;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import androidx.annotation.Nullable;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class AddDeviceActivity extends BaseActivity implements View.OnClickListener {
    RelativeLayout relativeLayout;
    RelativeLayout btnAddDevice;
    ImageView btnBack;

    //设备厂家的编号，14-海康,16-大华,53-宇视,48-onvif, 50-天地伟业, 36-巨峰/雄迈, 74-海 康 EHome, 76-rtsp, 103-28181 设备
    EditText tv_pluginid;
    //设备名称
    EditText tv_name;
    //主机的 IP 地址（rtsp 时为完整的 url）
    EditText tv_ip;
    //主机的端口
    EditText tv_port;
    //主机的序列号，可以不填
    EditText tv_sn;
    //设备的用户名
    EditText tv_deviceusername;
    //设备的密码
    EditText tv_devicepassword;
    //平台用户名
    EditText tv_username;
    //平台密码
    EditText tv_password;
    //设备的备注信息，如哪个施工单位等
    EditText tv_memo;
    //以"/"区分各级路径。如"test/demo"，则是二级路径，test 为第一级，demo 为第二级
    EditText tv_path;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_device);

        relativeLayout = findViewById(R.id.title_bar);
        btnBack = findViewById(R.id.backBtn);
        btnAddDevice = findViewById(R.id.btn_add_device);
        btnBack.setOnClickListener(this);
        btnAddDevice.setOnClickListener(this);

        tv_pluginid = findViewById(R.id.tv_pluginid);
        tv_name = findViewById(R.id.tv_name);
        tv_ip = findViewById(R.id.tv_ip);
        tv_port = findViewById(R.id.tv_port);
        tv_sn = findViewById(R.id.tv_sn);
        tv_deviceusername = findViewById(R.id.tv_deviceusername);
        tv_devicepassword = findViewById(R.id.tv_devicepassword);
        tv_username = findViewById(R.id.tv_username);
        tv_password = findViewById(R.id.tv_password);
        tv_memo = findViewById(R.id.tv_memo);
        tv_path = findViewById(R.id.tv_path);
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.backBtn:
                AddDeviceActivity.this.finish();
                break;

            case R.id.btn_add_device:
                String paramPluginid = tv_pluginid.getText().toString().trim();
                String paramName = tv_pluginid.getText().toString().trim();
                String paramIp = tv_pluginid.getText().toString().trim();
                String paramPort = tv_pluginid.getText().toString().trim();
                String paramSn = tv_pluginid.getText().toString().trim();//可以为空
                String paramDeviceusername = tv_pluginid.getText().toString().trim();
                String paramDevicepassword = tv_pluginid.getText().toString().trim();
                String paramUsername = ACache.get(AddDeviceActivity.this).getAsString("name");
//                String paramUsername = tv_pluginid.getText().toString().trim();
                String paramPassword = ACache.get(AddDeviceActivity.this).getAsString("pass");
//                String paramPassword = tv_pluginid.getText().toString().trim();
                String paramMemo = paramUsername + paramPassword;
//                String paramMemo = tv_pluginid.getText().toString().trim();
                String paramPath = tv_pluginid.getText().toString().trim();
                if (paramPluginid.isEmpty() || paramName.isEmpty() || paramIp.isEmpty() || paramPort.isEmpty()
                        || paramDeviceusername.isEmpty() || paramDevicepassword.isEmpty() || paramUsername.isEmpty() || paramPassword.isEmpty()
                        || paramMemo.isEmpty() || paramPath.isEmpty()) {
                    Toast.makeText(AddDeviceActivity.this, "必要参数不能为空", Toast.LENGTH_SHORT).show();
                } else {
                    CommonOkHttpClient.FUNC_TASK.execute(new Runnable() {
                        @Override
                        public void run() {
                            OkHttpClient client = new OkHttpClient().newBuilder()
                                    .build();
                            String url = "http://daxun.tpddns.cn:81/AddVideoDevice?pluginid=" + paramPluginid + "&name=" + paramName + "&ip=" + paramIp + "&port=" + paramPort + "&sn=" + paramSn + "&deviceusername=" + paramDeviceusername + "&devicepassword=" + paramDevicepassword + "&path=" + paramPath + "&username=" + paramUsername + "&password=" + paramPassword + "&memo=" + paramMemo;
                            Request request = new Request.Builder()
                                    .url(url)
                                    .method("GET", null)
                                    .addHeader("content-type", "form-data")
                                    .addHeader("Cookie", "IDHTTPSESSIONID=r4EN2qalGkkbZUS")
                                    .build();
                            try {
                                Response response = client.newCall(request).execute();
                                String res2 = response.body().string();
                                if (!TextUtils.isEmpty(res2)) {
                                    JSONObject jsonObject = new JSONObject(res2);
                                    int result = jsonObject.optInt("result");
                                    if (result == 0) {
                                        runOnUiThread(new Runnable() {
                                            @Override
                                            public void run() {
                                                Toast.makeText(AddDeviceActivity.this, "添加成功!", Toast.LENGTH_SHORT).show();
                                                AddDeviceActivity.this.finish();
                                            }
                                        });
                                    }
                                }
                            } catch (IOException e) {
                                e.printStackTrace();
                            } catch (ClassCastException e) {
                                e.printStackTrace();
                            } catch (JsonSyntaxException e) {
                                e.printStackTrace();
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    });
                }
                break;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        //解决相对布局下存在 layout_alignParentBottom="true" 元素时，点击edittext会将布局上顶
//        PreventKeyboardBlockUtil.getInstance(this).setBtnView(relativeLayout).register();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //释放资源
//        PreventKeyboardBlockUtil.getInstance(this).unRegister();
    }

}
